package cn.rengy.web.excelcompare.service;

import cn.rengy.tool.core.IdGenerator;
import cn.base.web.sys.pub.upload.entity.SysPubFileInfo;
import cn.base.web.sys.pub.upload.service.PubFileService;
import cn.base.web.sys.pub.upload.service.SysFileVO;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.StrUtil;
import cn.rengy.isql.*;
import cn.rengy.web.excelcompare.entity.*;
import cn.rengy.lang.BusinessException;
import cn.rengy.lang.ResultEntity;
import cn.rengy.tool.core.util._NumberUtils;
import cn.rengy.tool.excel.*;
import cn.rengy.util.ExceptionPrintUtils;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.ParserContext;
import org.springframework.expression.common.TemplateParserContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import jakarta.servlet.http.HttpServletResponse;

import java.io.*;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
@Slf4j
public class ExcelComporeService {


    @Autowired
    private Dao dao;
    @Autowired
    private NamedSqlDao namedSqlDao;
    @Autowired
    private DbService dbService;
    /**
     * 导入模板设置表头
     * @param excelConfigId
     * @param inputStream
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ResultEntity importExcelHeader(Long excelConfigId, InputStream inputStream){
        if(excelConfigId==0){
            return ResultEntity.fail("请选择要配置表头的报表信息");
        }
        ExcelConfigPO excelConfig=this.getExcelConfig(excelConfigId);
        int sheetNumber= _NumberUtils.toInt(excelConfig.getSheetNumber(),1);
        int bodyStartRowNumber=_NumberUtils.toInt(excelConfig.getBodyStartRowNumber(),1);;
        int sheetIndex=sheetNumber-1;
        int dataStartRowIndex=bodyStartRowNumber-1;
        //清除数据
        this.dao.update("delete from excel_header where excel_config_id=?",excelConfigId);
        EasyExcel.read(inputStream, new AnalysisEventListener<Map<Integer, String>>() {
                    private List<Map<Integer, String>> cachedHeaderList = new ArrayList<>();
                    @Override
                    public void invoke(Map<Integer, String> rowData, AnalysisContext analysisContext) {
                        int rowIndex=analysisContext.readRowHolder().getRowIndex();
                        if(rowIndex<dataStartRowIndex){
                            cachedHeaderList.add(rowData);
                        }
                    }

                    @Override
                    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                        saveHeader( excelConfigId, cachedHeaderList);
                    }
                }
        ).sheet(sheetIndex).headRowNumber(0).doRead();
        //导入模板后重新设置字段名称
        this.setColumnTitle(excelConfigId);
        //设置字段名称后重新设置字段映射
        reSetColumnMapping(excelConfigId);
        return ResultEntity.ok();
    }
    /**
     * 导入数据
     * @param inputStream
     */
    public void importData(Long taskId, Long reportId, InputStream inputStream, int isAppend) throws IOException {
        //查询任务id
        ExcelCompareTaskPO dataCompareTaskPO=this.dao.queryForBean("select * from excel_compare_task where id=?", ExcelCompareTaskPO.class,taskId);
        Long compareConfigId=dataCompareTaskPO.getCompareConfigId();
        //校验reportName是否正确,data_compare_config_detail
        Long configDetailId=this.dao.querySingleColumn("select id from excel_compare_config_detail where compare_config_id=? and report_id=?",Long.class,compareConfigId,reportId);
        if(configDetailId==null){
            throw new BusinessException("配置不存在，请检查reportName是否正确");
        }
        //根据reportName查询配置信息
        ExcelConfigPO dataExcelConfigPO=this.dao.queryForBean("select * from excel_config where id=?", ExcelConfigPO.class,reportId);

        String tableName=dataExcelConfigPO.getTableName();
//        String checkCell=dataExcelConfigPO.getCheckCell();
//        String checkValue=dataExcelConfigPO.getCheckValue();
//        CellPosition cellPosition=ExcelUtil.getCellPosition(checkCell);

        //清空数据
        if(isAppend==0){
            this.dao.update("delete from "+tableName+" where task_id=?",taskId);
        }
        int sheetNumber= _NumberUtils.toInt(dataExcelConfigPO.getSheetNumber(),1);
        int bodyStartRowNumber=_NumberUtils.toInt(dataExcelConfigPO.getBodyStartRowNumber(),1);;
        int sheetIndex=sheetNumber-1;
        int dataStartRowIndex=bodyStartRowNumber-1;
        //查询数据库header配置
        List<Map<String, Object>> dbHeaderList =this.dao.queryForList("select * from excel_header where excel_config_id=?",reportId);
        //使用EasyExcel读取
        EasyExcel.read(inputStream, new AnalysisEventListener<Map<Integer, String>>() {

            private List<Map<Integer, String>> readHeaderList = new ArrayList<>();
            private List<Map<Integer, String>> cachedDataList = new ArrayList<>();
            @Override
            public void invoke(Map<Integer, String> rowData, AnalysisContext analysisContext) {
                int rowIndex=analysisContext.readRowHolder().getRowIndex();
                if(rowIndex<dataStartRowIndex){
                    readHeaderList.add(rowData);
                }else{
                    cachedDataList.add(rowData);
                }
                //校验上传文件是否正确
    //                        if(cellPosition!=null){
    //                            int rowNumber=cellPosition.getRowNumber();
    //                            if(rowIndex==(rowNumber-1)){
    //                                String cellValue=rowData.get(cellPosition.getCellNumber()-1);
    //                                if(!Objects.equals(cellValue,checkValue)){
    //                                    throw new BusinessException("excel校验不通过，请检查是否上传的文件是否是"+dataExcelConfigPO.getReportName());
    //                                }
    //                            }
    //                        }
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                //校验表头是否一致
                ResultEntity r=checkHeader( dbHeaderList, readHeaderList);
                if(!r.isSuccess()){
                    throw new BusinessException(r.getMessage());
                }
                saveData( taskId, dataStartRowIndex, tableName, cachedDataList);
            }
        }
        ).sheet(sheetIndex).headRowNumber(0).doRead();

        //File file1=new File(filePath);
        //自写读取方法
//        ExcelRead.read(new ExcelRead.RowHandler() {
//            @Override
//            public void handleRow(List<Map<Integer, String>> rowList) {
//                saveData( taskId, dataStartRowIndex, tableName, rowList);
//            }
//        }, inputStream, sheetIndex);

        //导入完成

    }

    private ResultEntity checkHeader(List<Map<String, Object>> dbHeaderList,List<Map<Integer, String>> readHeaderList){
        if(dbHeaderList.size()!=readHeaderList.size()){
            return ResultEntity.fail("表头格式校验失败:表头行数不一致");
        }
        for(int i=0;i<dbHeaderList.size();i++){
            Map<String, Object> dbRow=dbHeaderList.get(i);
            Map<Integer, String> readRow=readHeaderList.get(i);
            for(int j=1;j<101;j++){
                String columnName= ExcelUtil.columnNumberToName(j).toLowerCase();
                String dbValue=MapUtils.getString(dbRow,columnName);
                String readValue=MapUtils.getString(readRow,j-1);
                if(!equalsCellValue(dbValue , readValue)){
                    return ResultEntity.fail("表头校验失败：["+columnName+(i+1)+"]的期望值["+dbValue+"],实际值["+readValue+"]");
                }
            }
        }
        return ResultEntity.ok();
    }
    private boolean equalsCellValue(String arg1,String arg2){
        if(arg1==null||arg1.length()==0){
            if(arg2==null){
                return true;
            }else{
                if(arg2.length()==0){
                   return true;
                }else{
                    return false;
                }
            }
        }else{
            if(arg2==null){
                return false;
            }else{
                if(arg2.length()==0){
                    return false;
                }else{
                    return arg1.equals(arg2);
                }
            }
        }
    }
//    public void test(){
//        List<ExcelCellMappingPO> list=this.dao.queryForBeanList("select * from excel_cell_mapping",ExcelCellMappingPO.class);
//        for(ExcelCellMappingPO c:list){
//            String data1Column=c.getData1Column().replace("data","");
//            String data2Column=c.getData2Column().replace("data","");
//            this.dao.update("update excel_cell_mapping set data1_column=? where id=?",ExcelUtil.columnNumberToName(Integer.parseInt(data1Column)),c.getId());
//            this.dao.update("update excel_cell_mapping set data2_column=? where id=?",ExcelUtil.columnNumberToName(Integer.parseInt(data2Column)),c.getId());
//        }
//    }

    /**
     * 设置表头后重置字段映射
     * @param excelConfigId excel配置id
     */
    private void reSetColumnMapping(Long excelConfigId){
        //根据excel配置id查询相关的比较定义
        List<ExcelCompareConfigPO> excelCompareConfigList=dao.queryForBeanList("select DISTINCT cc.* from  excel_compare_config_detail cd join excel_compare_config cc on cc.id=cd.compare_config_id where cd.report_id=?",ExcelCompareConfigPO.class,excelConfigId);
        for(ExcelCompareConfigPO excelCompareConfig:excelCompareConfigList){
            Long compareConfigId=excelCompareConfig.getId();

            List<ExcelCompareConfigDetailPO> configDetailList=this.getConfigDetai(compareConfigId);
            if(configDetailList.size()<2){
                throw new RuntimeException("缺少配置ExcelCompareConfigDetail");
            }
            Map<Long,ExcelConfigPO> configMap=new HashMap<>();
            for(ExcelCompareConfigDetailPO c:configDetailList){
                configMap.put(c.getReportId(),this.getExcelConfig(c.getReportId()));
            }
            ExcelConfigPO configOne= configMap.get(excelConfigId);
            ExcelConfigPO configTwo= getOtherOne(configMap,excelConfigId);
            if(StringUtils.isNotBlank(configOne.getMapColumn())&&
                    StringUtils.isNotBlank(configTwo.getMapColumn())){
                //查询title
                List<ExcelColumnTitlePO> titleList=this.dao.queryForBeanList("select * from excel_column_title where report_id=? order by id asc",ExcelColumnTitlePO.class,configOne.getId());
                //清空excel_cell_mapping
                this.dao.update("delete from excel_cell_mapping where compare_config_id=?",compareConfigId);
                for(ExcelColumnTitlePO title:titleList){
                    this.dao.update("insert into excel_cell_mapping(id,compare_config_id,"+configOne.getMapColumn()+","+configTwo.getMapColumn()+",title) values(?,?,?,(select max(cell_name) from excel_column_title where report_id=? and title=? having count(id)=1),?)",
                            IdGenerator.nextId(),compareConfigId,title.getCellName(),configTwo.getId(),title.getTitle(),title.getTitle());
                }
            }

        }
    }
    /**
     * 设置字段名称
     * @param reportId
     */
    private void setColumnTitle(Long reportId){
        //先清空
        this.dao.update("delete from excel_column_title where report_id=?",reportId);
        ExcelConfigPO excelConfigPO=this.getExcelConfig(reportId);
        String titleRowNumber=excelConfigPO.getTitleRowNumber();
        if(StringUtils.isNotBlank(titleRowNumber)){
            String []titleRowNumberArr=titleRowNumber.split(",");
            List<Map<String,Object>> headerList=this.dao.queryForList("select * from excel_header where excel_config_id=?",reportId);

            for(int i=1;i<maxCellNum;i++){
                String cellName=ExcelUtil.columnNumberToName(i).toLowerCase();
                String title=getTitleFromHeader( headerList, titleRowNumberArr, cellName);
                if(StringUtils.isNotBlank(title)){
                    //去掉换行
                    title= CharSequenceUtil.removeAllLineBreaks(title);
                    // title=title.replace("\n","").replace("\r","");
                    this.dao.update("insert excel_column_title(id,report_id,cell_name,title) values(?,?,?,?)"
                            ,IdGenerator.nextId(),reportId,cellName,title);
                }
            }
        }
    }

    private String getTitleFromHeader(List<Map<String,Object>> headerList,String []titleRowNumberArr,String cellName){
        String title=null;
        for(String n:titleRowNumberArr){
            int rowNumber=Integer.parseInt(n);
            title=(String)headerList.get(rowNumber-1).get(cellName);
            if(StringUtils.isNotBlank(title)){
                break;
            }
        }
        return title;
    }
    public static final int maxCellNum=150;
    private void saveHeader(Long excelConfigId,List<Map<Integer, String>> headerList){
        Map<String, Object>[] batchValues=new Map[headerList.size()];
        for(int j=0;j<headerList.size();j++){
            Map<Integer, String> row=headerList.get(j);//行数据
            Map<String,Object> param=new HashMap<String,Object>();
            param.put("Id", IdGenerator.nextId());
            param.put("excelConfigId",excelConfigId);
            param.put("rowNumber",j+1);
            Iterator<Map.Entry<Integer, String>> iterator=row.entrySet().iterator();
            while(iterator.hasNext()){
                Map.Entry<Integer, String> entry=iterator.next();
                int cellIndex=entry.getKey();
                String cellValue=entry.getValue();
                String cellName=ExcelUtil.columnNumberToName(cellIndex+1);
                if(cellIndex<maxCellNum){
                    param.put(cellName.toLowerCase(),cellValue);
                }else{
                    log.warn("忽略cell[{}]最大支持100列",cellName);
                }
            }
//            for(int i=0;i<row.size();i++){
//                String cellValue=row.get(i);
//                param.put("data"+(i+1),cellValue);
//            }
            batchValues[j]=param;
            //dbService.updateMapParameter( "insert_"+tableName,param);
            //System.out.println("22222");
        }
        dbService.batchUpdate("insert_excel_header",batchValues);
        headerList.clear();
    }
    private void saveData(Long taskId,int dataStartRowIndex,String tableName,List<Map<Integer, String>> rowList){
        Map<String, Object>[] batchValues=new Map[rowList.size()];
        for(int j=0;j<rowList.size();j++){
            Map<Integer, String> row=rowList.get(j);//行数据
            Map<String,Object> param=new HashMap<String,Object>();
            param.put("Id", IdGenerator.nextId());
            param.put("taskId",taskId);
            param.put("rowNumber",j+1);
//            if(j<dataStartRowIndex){
//                param.put("isHeader",1);
//            }else{
//                param.put("isHeader",0);
//            }
            Iterator<Map.Entry<Integer, String>> iterator=row.entrySet().iterator();
            while(iterator.hasNext()){
                Map.Entry<Integer, String> entry=iterator.next();
                int cellIndex=entry.getKey();
                String cellValue=entry.getValue();
                String cellName=ExcelUtil.columnNumberToName(cellIndex+1);
                if(cellIndex<maxCellNum){
                    param.put(cellName.toLowerCase(),cellValue);
                }else{
                    log.warn("忽略cell[{}]最大支持100列",cellName);
                }
            }
//            for(int i=0;i<row.size();i++){
//                String cellValue=row.get(i);
//                param.put("data"+(i+1),cellValue);
//            }
            batchValues[j]=param;
            //dbService.updateMapParameter( "insert_"+tableName,param);
            //System.out.println("22222");
        }
        dbService.batchUpdate("insert_"+tableName,batchValues);
        rowList.clear();
    }

    private ExcelConfigPO getExcelConfig(Long reportId){
        return this.dao.queryForBean("select * from excel_config where id=?", ExcelConfigPO.class,reportId);
    }

    private ExcelCompareTaskPO getTask(Long taskId){
        return this.dao.queryForBean("select * from excel_compare_task where id=?", ExcelCompareTaskPO.class,taskId);
    }
    private List<ExcelCompareConfigDetailPO> getConfigDetai(Long compareConfigId){
        return this.dao.queryForBeanList("select * from excel_compare_config_detail where compare_config_id=?", ExcelCompareConfigDetailPO.class,compareConfigId);
    }
    private ExcelCompareConfigPO getExcelCompareConfigPO(Long compareConfigId){
        return dao.queryForBean("select * from excel_compare_config where id=?",ExcelCompareConfigPO.class,compareConfigId);
    }


    private ExecutorService executorService= Executors.newFixedThreadPool(1);

    /**
     * 逐列比较字段
     * @param taskId
     * @throws IOException
     */
    private List<SheetObject> compareColumnResult(Long taskId) throws IOException {
        List<SheetObject> sheetList=new ArrayList<>();
        ExcelCompareTaskPO dataCompareTaskPO=getTask(taskId);
        Long compareConfigId=dataCompareTaskPO.getCompareConfigId();
        List<ExcelCompareConfigDetailPO> configDetailList=this.getConfigDetai(compareConfigId);
        Map<Long,ExcelConfigPO> configMap=new HashMap<>();
        for(ExcelCompareConfigDetailPO c:configDetailList){
            configMap.put(c.getReportId(),this.getExcelConfig(c.getReportId()));
        }
        ExcelConfigPO configOne=getExcelConfig(configDetailList.get(0).getReportId());
        ExcelConfigPO configTwo=getExcelConfig(configDetailList.get(1).getReportId());
        //定义样式
        CellStyleObject cellStyleObject=CellStyleObject.instance();
        CellStyleObject cellStyleYellow=CellStyleObject.instance().setForegroundColorYELLOW();
        //汇总数据sheet页
        SheetObject sheetObject1=new SheetObject();
        sheetObject1.setSheetName("字段差异比较汇总");
        List<Map<Integer, CellObject>> sheet1DataList =new ArrayList<Map<Integer,CellObject>>();
        sheetObject1.setShheetData(sheet1DataList);
        sheetList.add(sheetObject1);
        //int sheet1Index=-1;

        Map<Integer,CellObject> sheet1row1=new HashMap<Integer,CellObject>();
        sheet1row1.put(0,CellObject.instance(cellStyleYellow).setText("指标"));
        sheet1row1.put(1,CellObject.instance(cellStyleYellow).setText("一致个数"));
        sheet1row1.put(2,CellObject.instance(cellStyleYellow).setText("不一致个数"));
        sheet1DataList.add(sheet1row1);
        //明细sheet
        SheetObject sheetObject2=new SheetObject();
        sheetObject2.setSheetName("字段差异比较明细");
        List<Map<Integer, CellObject>> dataList =new ArrayList<Map<Integer,CellObject>>();
        sheetObject2.setShheetData(dataList);
        sheetList.add(sheetObject2);
        //int rowIndex=-1;

        Map<Integer,CellObject> row1=new HashMap<Integer,CellObject>();

        List<Map<String,Object>> cellMappingList=this.dao.queryForList("select * from excel_cell_mapping where compare_config_id=? and data1_column is not null and data2_column is not null order by id asc",compareConfigId);

        int row1CellIndex=-1;
        for(int i=0;i<cellMappingList.size();i++){
            Map<String,Object> c=cellMappingList.get(i);
            c.put("sameCount",0);
            c.put("notSameCount",0);
            String title=MapUtils.getString(c,"title");
            String configOneColumn=MapUtils.getString(c,StrUtil.toCamelCase(configOne.getMapColumn()));
            String configTwoColumn=MapUtils.getString(c,StrUtil.toCamelCase(configTwo.getMapColumn()));
            CellObject cellObject2=CellObject.instance(cellStyleYellow).setText("["+title+"]是否一致");//["+c.getTitle()+"]
            row1.put(++row1CellIndex,cellObject2);
            CellObject cellObject3=CellObject.instance(cellStyleObject).setText("["+configOne.getShortName()+"]["+configOneColumn+"]的值");//["+c.getTitle()+"]
            row1.put(++row1CellIndex,cellObject3);
            CellObject cellObject4=CellObject.instance(cellStyleObject).setText("["+configTwo.getShortName()+"]["+configTwoColumn+"]的值");//["+c.getTitle()+"]
            row1.put(++row1CellIndex,cellObject4);
        }
        dataList.add(row1);

        //1.查询要更新的表数据
        List<Map<String,Object>> list=this.dao.queryForList("select * from "+configOne.getTableName()+" where task_id=? and map_id is not null",taskId);
        //Map<String,String> cellMap=getCellMapping(taskId, configMap,configOne.getReportName());
        for(Map<String,Object> oneData:list){
            //Long oneId=MapUtils.getLong(oneData,"id");
            Long twoId=MapUtils.getLong(oneData,"mapId");
            Map<String,Object> twoData=dao.queryForMap("select * from "+configTwo.getTableName()+" where _id=?",twoId);
            //设置映射字段
            Map<Integer,CellObject> row=new HashMap<Integer,CellObject>();
            int rowCellIndex=-1;
            for(int i=0;i<cellMappingList.size();i++){
                Map<String,Object> c=cellMappingList.get(i);
                int sameCount=(int)c.get("sameCount");
                int notSameCount=(int)c.get("notSameCount");
                String oneCloumn=MapUtils.getString(c,StrUtil.toCamelCase(configOne.getMapColumn()));
                String twoCloumn=MapUtils.getString(c,StrUtil.toCamelCase(configTwo.getMapColumn()));
                String oneValue=MapUtils.getString(oneData,oneCloumn);
                String towValue=MapUtils.getString(twoData,twoCloumn);
                boolean isSame=Objects.equals(oneValue, towValue);
                String sameText=isSame?"一致":"不一致";
                if(isSame){
                    sameCount++;
                }else{
                    notSameCount++;
                }
                c.put("sameCount",sameCount);
                c.put("notSameCount",notSameCount);
                CellObject cellObject1=CellObject.instance(cellStyleObject).setText(sameText);
                row.put(++rowCellIndex,cellObject1);
                CellObject cellObject2=CellObject.instance(cellStyleObject).setText(oneValue);
                row.put(++rowCellIndex,cellObject2);
                CellObject cellObject3=CellObject.instance(cellStyleObject).setText(towValue);
                row.put(++rowCellIndex,cellObject3);
                //更新字段比较结果
                //dao.update("update "+configOne.getTableName()+" set flag2='"+sameText+"' where id=?",taskId);
                //dao.update("update "+configTwo.getTableName()+" set flag2='"+sameText+"' where id=?",taskId);


            }
            dataList.add(row);
        }
        //汇总结果
        for(int i=0;i<cellMappingList.size();i++) {
            Map<String, Object> c = cellMappingList.get(i);
            String title=MapUtils.getString(c,"title");
            int sameCount = (int) c.get("sameCount");
            int notSameCount = (int) c.get("notSameCount");
            Map<Integer,CellObject> sheet1row=new HashMap<Integer,CellObject>();
            sheet1row.put(0,CellObject.instance(cellStyleObject).setText(title));
            sheet1row.put(1,CellObject.instance(cellStyleObject).setText(sameCount+""));
            sheet1row.put(2,CellObject.instance(cellStyleObject).setText(notSameCount+""));
            sheet1DataList.add(sheet1row);
        }


        //response.setContentLengthLong(file.length());

        return sheetList;
    }


    private void generateZip(ExcelCompareConfigPO excelCompareConfigPO, Long file_item_id, Long taskId, List<ExcelCompareConfigDetailPO> configDetailList) throws IOException {

        SheetObject sheetObject1=new SheetObject();
        sheetObject1.setSheetName("数据匹配结果");
        List<Map<Integer, CellObject>> dataList =new ArrayList<Map<Integer,CellObject>>();
        sheetObject1.setShheetData(dataList);
        //int rowIndex=-1;

        CellStyleObject titleCellStyle=CellStyleObject.instance();
        titleCellStyle.setForegroundColorYELLOW();
        CellStyleObject bodyCellStyleObject=CellStyleObject.instance();
        boolean isHaveDuplicate=false;//是否有重复数据
        for(ExcelCompareConfigDetailPO configDetail:configDetailList){
            Long reportId=configDetail.getReportId();
            ExcelConfigPO dataExcelConfigPO=getExcelConfig(reportId);
            String reportName=dataExcelConfigPO.getShortName();
            String tableName=dataExcelConfigPO.getTableName();
            String keyColumnName=dataExcelConfigPO.getKeyColumnName();
            //查询总条数
            Long c=this.dao.querySingleColumn("select count(*) c from "+tableName+" where task_id=?",Long.class,taskId);
            Map<Integer,CellObject> countR=new HashMap<Integer,CellObject>();
            countR.put(0,CellObject.instance(titleCellStyle)
                    .setText("["+reportName+"]总共"+c.intValue()+"条数据"));
            dataList.add(countR);
            //查询空格数据
            List<Map<String,Object>> blankList=this.dao.queryForList("select "+keyColumnName+" from "+tableName+" where task_id=? and "+keyColumnName+" like '% %'",taskId);
            if(blankList.size()>0){
                Map<Integer,CellObject> r1=new HashMap<Integer,CellObject>();
                CellObject h1=CellObject.instance(titleCellStyle)
                        .setText("["+reportName+"]有空格数据"+blankList.size()+"条");
                r1.put(0,h1);
                dataList.add(r1);
                for(Map<String,Object> map:blankList){
                    String data=MapUtils.getString(map,keyColumnName);
                    dataList.add(Collections.singletonMap(0,CellObject.instance(bodyCellStyleObject).setText(data)));
                }
                //删除空格数据
                this.dao.update("update "+tableName+" set "+keyColumnName+"=REPLACE("+keyColumnName+",' ','')  where task_id=? and "+keyColumnName+" like '% %'",taskId);
            }
            //清空标记
            dao.update("update "+tableName+" set flag1=null where task_id=? ",taskId);
            //查询重复数据
            List<Map<String,Object>> duplicateList=this.dao.queryForList("select max("+keyColumnName+") "+keyColumnName+" from "+tableName+" " +
                    " where task_id=?  group by  "+keyColumnName+" having count(_id)>1",taskId);
            if(!duplicateList.isEmpty()){
                isHaveDuplicate=true;
                dataList.add(Collections.singletonMap(0,CellObject.instance(titleCellStyle)
                        .setText("["+reportName+"]重复数据"+duplicateList.size()+"条")));
                for(Map<String,Object> map:duplicateList){
                    String data=MapUtils.getString(map,keyColumnName);
                    dataList.add(Collections.singletonMap(0,CellObject.instance(bodyCellStyleObject).setText(data)));
                    //标记重复数据
                    dao.update("update "+tableName+" set flag1='duplicate' where task_id=? and "+keyColumnName+"=?",taskId,data);
                }
            }
        }
        ExcelConfigPO configOne=getExcelConfig(configDetailList.get(0).getReportId());
        ExcelConfigPO configTow=getExcelConfig(configDetailList.get(1).getReportId());
        StandardEvaluationContext context = new StandardEvaluationContext();
        ExpressionParser parser = new SpelExpressionParser();
        TemplateParserContext templateParserContext=new TemplateParserContext();
        context.setVariable("configOne", configOne);
        context.setVariable("configTow", configTow);


        //查询两个表相同数据
        String expressionSql="select  count(*) c from \n" +
                "#{#configOne.tableName} join  #{#configTow.tableName}\n" +
                "on #{#configOne.tableName}.#{#configOne.keyColumnName}=#{#configTow.tableName}.#{#configTow.keyColumnName}\n" +
                "where #{#configOne.tableName}.task_id=? and #{#configTow.tableName}.task_id=? ";
        Expression expression = parser.parseExpression(expressionSql, templateParserContext);
        String sql=expression.getValue(context, String.class);
//            GenericTokenParser parser=new GenericTokenParser("#","#",new TokenHandler() {
//                @Override
//                public String handleToken(String content) {
//
//                    return dataMap.get(content);
//                }
//
//            });
        Long equalCount=this.dao.querySingleColumn(sql,Long.class
                ,taskId,taskId);
        dataList.add(
                Collections.singletonMap(0,CellObject.instance(titleCellStyle).setText("相同数据"+equalCount+"条")));

        //if(!isHaveDuplicate){//没有重复数据
        //设置映射table、id
        String expressionSetSql1="update #{#configOne.tableName} d1 set d1.map_id=\n" +
                "(select d2._id from #{#configTow.tableName} d2 where d2.flag1 is null and d2.task_id=?   and d1.#{#configOne.keyColumnName}= d2.#{#configTow.keyColumnName}) where d1.task_id=? and d1.flag1 is null";
        String expressionSetSql2="update #{#configTow.tableName} d2 set d2.map_id=\n" +
                "(select d1._id from #{#configOne.tableName} d1 where task_id=? and d1.map_id=d2._id) where d2.task_id=?";

        String setSql1=parser.parseExpression(expressionSetSql1, templateParserContext).getValue(context, String.class);
        this.dao.update(setSql1,taskId,taskId);
        String setSql2=parser.parseExpression(expressionSetSql2, templateParserContext).getValue(context, String.class);
        this.dao.update(setSql2,taskId,taskId);

        Long matchCount=this.dao.querySingleColumn("select count(*) c from "+configOne.getTableName()+" where task_id=? and map_id is not null",Long.class
                ,taskId);
        dataList.add(
                Collections.singletonMap(0,CellObject.instance(titleCellStyle).setText("匹配数据"+matchCount+"条")));

        //不匹配数据
        //表1多的数据
        String unMatchSql1="select "+configOne.getKeyColumnName()+" from "+configOne.getTableName()+" where task_id=?  and map_id is null";
        List<String> unMatchList1=this.dao.querySingleColumnForList(unMatchSql1,String.class,taskId);
        dataList.add(Collections.singletonMap(0,CellObject.instance(titleCellStyle)
                .setText("["+configOne.getShortName()+"]多的数据"+unMatchList1.size()+"条")));
        for(String t:unMatchList1){
            dataList.add(Collections.singletonMap(0, CellObject.instance( bodyCellStyleObject).setText(t)));
        }
        //表2多的数据
        String unMatchSql2="select "+configTow.getKeyColumnName()+" from "+configTow.getTableName()+" where task_id=? and map_id is null";
        List<String> unMatchList2=this.dao.querySingleColumnForList(unMatchSql2,String.class,taskId);
        dataList.add(Collections.singletonMap(0,CellObject.instance(titleCellStyle)
                .setText("["+configTow.getShortName()+"]多的数据"+unMatchList2.size()+"条")));
        for(String t:unMatchList2){
            dataList.add(Collections.singletonMap(0,CellObject.instance( bodyCellStyleObject).setText(t)));
        }
        //}

        //response.setContentType("application/octet-stream");
        //response.setContentLengthLong(file.length());
        //String filename= _NetUtils.urlEncode("相同数据.xlsx");
        //response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=".concat(filename));
        SysPubFileInfo sysPubFileInfo=pubFileService.getPubFile(20862067816792064L);
        File dir=this.pubFileService.getSaveDir(sysPubFileInfo);
        File file=new File(dir,"["+excelCompareConfigPO.getCompareName()+"]比较结果.xlsx");

        List<SheetObject> sheetObjectList=new ArrayList<>(2);
        sheetObjectList.add(sheetObject1);
        sheetObjectList.addAll(compareColumnResult(taskId));
        SimpleExcelWrite.export2007(new FileOutputStream(file),sheetObjectList);
        SysFileVO sysFileVO=new SysFileVO();
        sysFileVO.setFile(file);
        sysFileVO.setOriginalFileName(file.getName());
        sysFileVO.setId(file_item_id);
        pubFileService.uploaded(sysPubFileInfo,  sysFileVO);
    }

    @Autowired
    private PubFileService pubFileService;

    /**
     * 导出excel数据
     * @param sqlname
     * @param taskId
     * @return
     */
    public ResultEntity exportExcelData(String sqlname,Long taskId) {
        Long file_item_id=IdGenerator.nextId();
        executorService.execute(() -> {
            try {
                doExportExcelData(sqlname,taskId,file_item_id);
            } catch (Exception e) {
                log.error(ExceptionPrintUtils.getTrace(e));
            }
        });
        return ResultEntity.ok(file_item_id);
    }
    private void doExportExcelData(String sqlname,Long taskId,Long file_item_id) throws IOException {
        CellStyleObject cellStyleObject=CellStyleObject.instance();
        List<SheetObject> sheetObjectList=new ArrayList<>();

        SheetObject sheetObject1=new SheetObject();
        sheetObject1.setSheetName("data");
        List<Map<Integer, CellObject>> sheet1DataList =new ArrayList<Map<Integer,CellObject>>();
        List<Map<String,Object>> dataList=dbService.queryForList(sqlname,taskId);
        for(int i=0;i<dataList.size();i++){
            Map<String,Object> data=dataList.get(i);
            Iterator<Map.Entry<String,Object>> ite=data.entrySet().iterator();
            Map<Integer, CellObject> cellMap=new HashMap<>();
            while(ite.hasNext()){
                Map.Entry<String,Object> entry=ite.next();
                String key=entry.getKey();
                Object value=entry.getValue();
                String text=value==null?null:value.toString();
                CellObject cellObject=CellObject.instance(cellStyleObject).setText(text);
                cellMap.put(ExcelUtil.columnNameToNumber(key)-1,cellObject);
            }
            sheet1DataList.add(cellMap);
        }
        sheetObject1.setShheetData(sheet1DataList);
        sheetObjectList.add(sheetObject1);

        SysPubFileInfo sysPubFileInfo=pubFileService.getPubFile(20862067816792064L);
        File dir=this.pubFileService.getSaveDir(sysPubFileInfo);
        File file=new File(dir,taskId+".xlsx");
        SimpleExcelWrite.export2007(new FileOutputStream(file),sheetObjectList);
        SysFileVO sysFileVO=new SysFileVO();
        sysFileVO.setFile(file);
        sysFileVO.setOriginalFileName(file.getName());
        sysFileVO.setId(file_item_id);
        pubFileService.uploaded(sysPubFileInfo,  sysFileVO);
    }
    /**
     * 导出分析结果
     */
    public ResultEntity exportCompareResult(Long taskId, HttpServletResponse response) throws IOException {
        ExcelCompareTaskPO dataCompareTaskPO=getTask(taskId);
        Long compareConfigId=dataCompareTaskPO.getCompareConfigId();
        ExcelCompareConfigPO excelCompareConfigPO=this.getExcelCompareConfigPO(compareConfigId);
        List<ExcelCompareConfigDetailPO> configDetailList=this.getConfigDetai(compareConfigId);
        if(configDetailList.size()<2){
            return ResultEntity.fail("缺少配置ExcelCompareConfigDetail");
        }
        Long file_item_id=IdGenerator.nextId();
        executorService.execute(() -> {
            try {
                generateZip( excelCompareConfigPO,file_item_id, taskId,configDetailList);
            } catch (Exception e) {
                log.error(ExceptionPrintUtils.getTrace(e));
            }
        });
        return ResultEntity.ok(file_item_id);

    }


//    public void handle(){
//        List<Map<String,Object>> all=this.dao.queryForList("select * from  data1");
//        String cityCode="";
//        String type="";
//        for(Map<String,Object> row:all) {
//            Object id = row.get("id");
//            String data1 = MapUtils.getString(row, "data1");
//            String data5 = MapUtils.getString(row, "data5");
//            String data6 = MapUtils.getString(row, "data6");
//
//            if(StringUtils.isNotBlank(data5)){
//                cityCode= data5;
//            }else{
//                this.dao.update("update data1 set data5=? where id=?",cityCode,id);
//            }
//
//            if(StringUtils.isNotBlank(data6)){
//                type= data6;
//            }else{
//                this.dao.update("update data1 set data6=? where id=?",type,id);
//            }
//
//        }
//    }

//    public void replaceName(){
//        List<Map<String,Object>> all=this.dao.queryForList("select * from data2 where data1 in (select data2 from data3)");
//        int i=0;
//        for(Map<String,Object> row:all){
//            Object id=row.get("Id");
//            String data1=MapUtils.getString(row,"data1");
//            Map<String,Object> data3=this.dao.queryForMap("select data1 from data3 where data2=?",data1);
//            if(data3!=null){
//                Object newName=data3.get("data1");
//                this.dao.update("update data2 set data1=? where id=?",newName,id);
//                i++;
//                System.out.println("第"+i+"条更新");
//            }
//        }
//    }

//    public void setmapping2(){
//        List<Map<String,Object>> list=dao.queryForList("select * from data1 where id=11558");
//        Map<String,Object> m=list.get(0);
//        Iterator<Map.Entry<String,Object>> ite=m.entrySet().iterator();
//        while(ite.hasNext()){
//            Map.Entry<String,Object> entry=ite.next();
//            String key=entry.getKey();
//            Object value=entry.getValue();
//            dao.update("update data_mapping set title=? where data1_column=?",value,key);
//        }
//    }
//    public  void setmapping(){
//        String t1="data1,data2,data3,data4,data5,data6,data7,data8,data9,data10,data11,data12,data13,data14,data15,data16,data17,data18,data19,data20,data21,data22,data23,data24,data25,data26,data27,data28,data29,data30,data31,data32,data33,data34,data35,data36,data37,data38,data39,data40,data41,data42,data43,data44,data45,data46,data47,data48,data49,data50,data51,data52,data53,data54,data55,data56,data57,data58,data59,data60,data61,data62,data63,data64,data65,data66,data67,data68,data69,data70,data71,data72,data73,data74,data75,data76";
//        String t2=",,data1,,data4,data5,data6,data7,data8,,,data9,data10,data11,data12,data13,data14,data15,data16,data17,data18,data19,data20,data21,data22,data23,data24,data25,data26,data27,data28,data29,data30,data31,data32,data33,data34,data35,data36,data37,data38,data39,data40,data43,data44,data45,data46,data47,data48,data49,data50,data51,data52,data53,data54,data55,data56,data57,data58,data59,data60,data61,data62,data63,data64,data65,data66,data67,data68,data69,data70,data71,data72,data73,data74,data76";
//        System.out.println(t1.split(",").length);
//        System.out.println(t2.split(",").length);
//        String [] arr1=t1.split(",");
//        String [] arr2=t2.split(",");
//        for(int i=0;i<arr1.length;i++){
//            String a1=arr1[i];
//            String a2=arr2[i];
//            if(StringUtils.isNotBlank(a1)&&
//                    StringUtils.isNotBlank(a2)){
//                dao.update("insert into data_mapping(data1_column,data2_column) values(?,?)",a1,a2);
//
//            }
//        }
//    }


    /**
     * 获取另一个表名
     * @return
     */
    private ExcelConfigPO getOtherOne(Map<Long,ExcelConfigPO> configMap,Long reportId){
        Iterator<Map.Entry<Long,ExcelConfigPO>> ite=configMap.entrySet().iterator();
        Map.Entry<Long,ExcelConfigPO> one=ite.next();
        if(reportId.equals(one.getKey())){
            return ite.next().getValue();
        }else{
            return one.getValue();
        }
    }

    private List<ExcelCellMappingPO> selectCellMapping(Long compareConfigId){
        List<ExcelCellMappingPO> list=this.dao.queryForBeanList("select * from excel_cell_mapping where compare_config_id=? and data1_column is not null and data2_column is not null",ExcelCellMappingPO.class,compareConfigId);
        return list;
    }
    /**
     *
     * @param taskId 比较任务id
     * @param configMap
     * @param reportId 此报表的的字段为key
     * @return
     */
    private Map<String,String> getCellMapping(Long taskId,Map<Long,ExcelConfigPO> configMap,Long reportId){
        List<Map<String,Object>> list=this.dao.queryForList("select * from excel_cell_mapping where compare_config_id=(select compare_config_id from excel_compare_task where id=?) and data1_column is not null and data2_column is not null",taskId);
        Map<String,String> map=new HashMap<String,String>();
        ExcelConfigPO configOne= configMap.get(reportId);
        ExcelConfigPO configOtherOne= getOtherOne(configMap,reportId);
        for(Map<String,Object> cellMap:list){
            String key=MapUtils.getString(cellMap,StrUtil.toCamelCase(configOne.getMapColumn()));
            String value=MapUtils.getString(cellMap,StrUtil.toCamelCase(configOtherOne.getMapColumn()));
            map.put(key,value);
        }
        return map;
    }

    private Map<String,String> getCellMappingByCompareConfigId(Long compare_config_id,Map<Long,ExcelConfigPO> configMap,Long reportId){
        List<Map<String,Object>> list=this.dao.queryForList("select * from excel_cell_mapping where compare_config_id=? and data1_column is not null and data2_column is not null",compare_config_id);
        Map<String,String> map=new HashMap<String,String>();
        ExcelConfigPO configOne= configMap.get(reportId);
        ExcelConfigPO configOtherOne= getOtherOne(configMap,reportId);
        for(Map<String,Object> cellMap:list){
            String key=MapUtils.getString(cellMap,StrUtil.toCamelCase(configOne.getMapColumn()));
            String value=MapUtils.getString(cellMap,StrUtil.toCamelCase(configOtherOne.getMapColumn()));
            map.put(key,value);
        }
        return map;
    }

//    public Map<String,Map<String,Object>> getDataMapping(String updateTo){
//        List<Map<String,Object>> list=this.dao.queryForList("select * from data_mapping where update_to=?",updateTo);
//        Map<String,Map<String,Object>> map=new HashMap<String,Map<String,Object>>();
//        for(Map<String,Object> m:list){
//            String column=MapUtils.getString(m,updateTo+"Column");
//            map.put(column,m);
//        }
//        return map;
//    }


    private Map<Long,ExcelConfigPO> getConfigByTask(Long taskId){
        ExcelCompareTaskPO dataCompareTaskPO=getTask(taskId);
        Long compareConfigId=dataCompareTaskPO.getCompareConfigId();
        List<ExcelCompareConfigDetailPO> configDetailList=this.getConfigDetai(compareConfigId);
        if(configDetailList.size()<2){
            throw new RuntimeException("缺少配置ExcelCompareConfigDetail");
        }
        Map<Long,ExcelConfigPO> configMap=new HashMap<>();
        for(ExcelCompareConfigDetailPO c:configDetailList){
            configMap.put(c.getReportId(),this.getExcelConfig(c.getReportId()));
        }
        return configMap;
    }
    private Map<Long,ExcelConfigPO> getConfigByCompareConfigId(Long compareConfigId){
        List<ExcelCompareConfigDetailPO> configDetailList=this.getConfigDetai(compareConfigId);
        if(configDetailList.size()<2){
            throw new RuntimeException("缺少配置ExcelCompareConfigDetail");
        }
        Map<Long,ExcelConfigPO> configMap=new HashMap<>();
        for(ExcelCompareConfigDetailPO c:configDetailList){
            configMap.put(c.getReportId(),this.getExcelConfig(c.getReportId()));
        }
        return configMap;
    }
    /**
     * 新增多的数据到目标表
     * @param fromReportId
     * @param toReportId
     */
    @Transactional(rollbackFor = Exception.class)
    public void insertTo(Long taskId,Long fromReportId,Long toReportId){
        //查询量表映射信息
        Map<Long,ExcelConfigPO> configMap=getConfigByTask(taskId);
        ExcelConfigPO fromReportConfig=configMap.get(fromReportId);
        ExcelConfigPO toReportConfig=configMap.get(toReportId);
        //1.查询源数据中多的
        String fromDataListSql=
                "select * from "+fromReportConfig.getTableName()+" where task_id=?  and map_id is null and insert_to='"+toReportConfig.getTableName()+"'";
        List<Map<String,Object>> fromDataList=this.dao.queryForList(fromDataListSql,taskId);
        Long maxRowNumber=this.dao.querySingleColumn("select max(`row_number`) c from "+toReportConfig.getTableName()+" where task_id=?",Long.class,taskId);
        Map<String,String> cellMap=getCellMapping(taskId, configMap,toReportId);
        for(Map<String,Object> fromData:fromDataList){
            //1.新增到目标表
            Long fromId=MapUtils.getLong(fromData,"Id");
            Long toId=IdGenerator.nextId();
            Map<String,Object> insertParam=new HashMap<String,Object>();
            insertParam.put("Id", toId);
            insertParam.put("taskId",taskId);
            insertParam.put("rowNumber",++maxRowNumber);
            insertParam.put("mapId", fromId);
            //设置映射字段
            Iterator<Map.Entry<String,String>> ite=cellMap.entrySet().iterator();
            while(ite.hasNext()){
                Map.Entry<String,String> entry=ite.next();
                String toCell= entry.getKey();
                String fromCell=entry.getValue();
                Object value=fromData.get(fromCell);
                insertParam.put(toCell, value);
            }
            dbService.updateMapParameter( "insert_"+toReportConfig.getTableName(),insertParam);
            //2.更新map_id
            this.dao.update("update "+fromReportConfig.getTableName()+" set map_id=?,insert_to=null where _id=?",toId,fromId);
        }

    }
    /**
     * 更新表
     */
//    public void updateTo(Long taskId,Long fromReportId,Long toReportId){
//        Map<Long,ExcelConfigPO> configMap=getConfigByTask(taskId);
//        ExcelConfigPO fromReportConfig=configMap.get(fromReportId);
//        ExcelConfigPO toReportConfig=configMap.get(toReportId);
//
//        //1.查询要更新的表数据
//        List<Map<String,Object>> list=this.dao.queryForList("select * from "+fromReportConfig.getTableName()+" where task_id=? and map_id is not null",taskId);
//        Map<String,String> cellMap=getCellMapping(taskId, configMap,toReportId);
//        for(Map<String,Object> fromData:list){
//            Long fromId=MapUtils.getLong(fromData,"Id");
//            Long toId=MapUtils.getLong(fromData,"mapId");
//            //设置映射字段
//            Iterator<Map.Entry<String,String>> ite=cellMap.entrySet().iterator();
//            while(ite.hasNext()){
//                Map.Entry<String,String> entry=ite.next();
//                String toCell= entry.getKey();
//                String fromCell=entry.getValue();
//                Object newValue=fromData.get(fromCell);
//                dao.update("update "+toReportConfig.getTableName()+" set "+toCell+"=? where _id=?",newValue,toId);
//            }
//        }
//    }

    /**
     * 更新统计表2
     * @param taskId
     */
    @Transactional(rollbackFor = Exception.class)
    public void staData2(Long taskId){
        //查询统计表输出表
        String tableName="excel_data3";
        ExcelCompareTaskPO compareTaskPO=getTask(taskId);
        Long compareConfigId=compareTaskPO.getCompareConfigId();
        Map<String,Object> param=new HashMap<>();
        param.put("taskId",taskId);
        //查询数据集
        List<ExcelStatDsConfigPO> dsList=this.dbService.queryForBeanList("select_excel_stat_ds_config",ExcelStatDsConfigPO.class,compareConfigId);
        //查询模板 excel_data3 为统计表
        List<Map<String,Object>> modelList=dbService.queryForList("select_excel_header_by_task_id",taskId);


        //StandardEvaluationContext context = new StandardEvaluationContext();
        //ExpressionParser parser = new SpelExpressionParser();
        //ParserContext templateParserContext=ParserContext.TEMPLATE_EXPRESSION;
        Map<String,Object> dataSet=new HashMap();
        //设置数据集
        for(ExcelStatDsConfigPO excelStatDsConfigPO:dsList){
            String dsName=excelStatDsConfigPO.getDsName();
            Map<String,Object> dsData=namedSqlDao.queryForMap(excelStatDsConfigPO.getDsSql(),new _MapSqlParameterSource(param));
            dataSet.put(dsName,dsData);
        }
        //context.setVariables(var);

        Configuration configuration=new Configuration();
        configuration.setDefaultEncoding("utf-8");

        //填充数据
        for(Map<String,Object> m:modelList){//数据
            Iterator<Map.Entry<String, Object>> it=m.entrySet().iterator();
            while(it.hasNext()){
                Map.Entry<String, Object> entry=it.next();
                String key=entry.getKey();
                String value=entry.getValue()==null?"":entry.getValue().toString();
                //if(value.startsWith("${")){

                    //替换
//                    try{
//                        Expression expression = parser.parseExpression(value, templateParserContext);
//                        String newValue=expression.getValue(context, String.class);
//                        m.put(key,newValue);
//                    }catch (Exception e){
//                        log.error(ExceptionPrintUtils.getTrace(e));
//                        //m.put(key,"seterror");
//                    }

                    try {
                        Template template = new Template(entry.toString(), value, configuration);
                        StringWriter writer = new StringWriter();
                        template.process(dataSet, writer);
                        m.put(key,writer.toString());
                    } catch (Exception e) {
                        log.error(ExceptionPrintUtils.getTrace(e));
                    }
                //}

            }
            m.put("taskId",taskId);
            m.put("Id",IdGenerator.nextId());
        }

        //先删除，再新增
        this.dao.update("delete from "+tableName+" where task_id=?",taskId);
        Map<String, Object>[] batchValues=modelList.toArray(new Map[modelList.size()]);
        this.dbService.batchUpdate("insert_"+tableName,batchValues);

    }

    public String spel(String content){
        ExpressionParser parser = new SpelExpressionParser();//定义spel解析器
        Expression expression = parser.parseExpression(content, ParserContext.TEMPLATE_EXPRESSION);//解析
        StandardEvaluationContext context = new StandardEvaluationContext();//表达式上下文
        return expression.getValue(context, String.class);
    }




    public void updateByUpdateConfigId(Long updateConfigId){
        ExcelUpdateConfigPO excelUpdateConfigPO=this.dao.queryForBean("select * from excel_update_config where id=?",ExcelUpdateConfigPO.class,updateConfigId);
        Long compareConfigId=excelUpdateConfigPO.getCompareConfigId();
        Map<Long,ExcelConfigPO> configMap=getConfigByCompareConfigId(compareConfigId);
        Long fromReportId=excelUpdateConfigPO.getUpdateFrom();
        Long toReportId=excelUpdateConfigPO.getUpdateTo();
        ExcelConfigPO fromReport=configMap.get(fromReportId);
        ExcelConfigPO toReport= configMap.get(toReportId);
        //ExcelConfigPO toReport= getOtherOne(configMap,fromReportId);
        Map<String,String> cellMap=getCellMappingByCompareConfigId(compareConfigId, configMap,fromReportId);
        List<Map<String,Object>> columnList=dao.queryForList("select * from excel_update_column where update_config_id=?",excelUpdateConfigPO.getId());
        List<Map<String,Object>> dataList=dao.queryForList(excelUpdateConfigPO.getQuerySql());
        for(Map<String,Object> data:dataList){
            Long fromId=MapUtils.getLong(data,"fromId");
            Long toId=MapUtils.getLong(data,"toId");
            for(Map<String,Object> column:columnList){
                String fromColumnName=MapUtils.getString(column,"fromColumnName");
                String toColumnName=cellMap.get(fromColumnName);
                dao.update("update "+toReport.getTableName()+" set `"+toColumnName+"` =(select `"+fromColumnName+"` from "+fromReport.getTableName()+" where _id=?) where _id=? ",fromId,toId);
            }

        }
    }
    public void doUpdate(Long taskId){

        ExcelCompareTaskPO dataCompareTaskPO=getTask(taskId);
        Long compareConfigId=dataCompareTaskPO.getCompareConfigId();
        //1.查询更新配置
        List<ExcelUpdateConfigPO> list=this.dao.queryForBeanList("select * from excel_update_config where compare_config_id=?", ExcelUpdateConfigPO.class,compareConfigId);
        //查询更新字段
        for(ExcelUpdateConfigPO excelUpdateConfigPO:list){
            updateByUpdateConfigId(excelUpdateConfigPO.getId());
        }
    }

}
